<?php

class UserController extends AppController
{
    var $uses = array("Post", "Track", "Site", "Like", "User", "Artist");
    var $componenets = array("Session");
    
    function login()
    {
        $this->Session->start();
        
        $user = $this->User->find(array('username' => $_POST['username'], 'password' => md5($_POST['password'])));

        if ($user)
        {
            $this->Session->write('User', $user['User']);
            $this->redirect('/post/home/'.$user['User']['username']);
        }
        
        exit;
    }
    
    function admin($page = 1)
    {
     	$this->layout = "admin";
    }
    
    function tracks_ajax()
    {
	    $sort = $_POST['sort'];
	    $sort = self::unflatten($sort).' '.$_POST['dir'];
	    
		$tracks = $this->Track->findAll(null, "Track.*, Track.status, Post.id, Post.link, Artist.id, Artist.name", $sort, $_POST['limit'], floor($_POST['start']/$_POST['limit']));
        $track_count = $this->Track->findCount();
		$tracks = self::flatten($tracks);

        foreach ($tracks as $i=>$track)
        {

	    	$tracks[$i]['functions'] = '<a href="javascript: updateTrack('.$track['Track-id'].')">Save</a>'; 
	    	$tracks[$i]['functions'] .= '<a href="/tracks/'.$track['Track-id'].'.mp3">Download</a>'; 
	    	$tracks[$i]['id'] = $track['Track-id'];   
	    	$tracks[$i]['filesize'] = number_format(filesize('tracks/'.$track['Track-id'].'.mp3')/1000, 2).' K';
        }
        
        echo json_encode(array('recordcount' => $track_count, 'data' => $tracks));
        exit;    
	}
   
    function artist_box()
    {
	    $query = $_POST['query'];
	    $artists = $this->Artist->query("SELECT `id`, `name` FROM artists WHERE name LIKE '$query%'");

	    $json = array();
	    foreach ($artists as $artist)
	    {
			   $json[] = array('Artist-name' => $artist['artists']['name']);
	    }
	    
	    echo json_encode(array('recordcount' => count($json), 'data' => $json));
	    exit;
    }
    
	function flatten($tracks)
	{
		$json = array();
		
        foreach($tracks as $track)
        {
	        $track_json = array();
	    	foreach ($track as $model => $part)
	    	{
		    	foreach ($part as $field => $val)
		    	{
	    			$track_json[$model.'-'.$field] = $val;
    			}
		    }
		    
		    $json[] = $track_json;
		    	   
        }	
        
        return $json;	
	}
	
	function unflatten($str)
	{
		$str = explode('-', $str);
		$str = $str[0].'.'.$str[1];
		
		return $str;	
	}
	
	function require_login()
	{
		$this->Session->start();

		$user = $this->Session->read('User');
		var_dump($user);
		exit;		
		if (!$user['id']) $this->redirect('/');
	}
}

?>
